package com.iqiyi.pps.epg.web.timer;

import com.google.common.util.concurrent.*;
import com.iqiyi.pps.epg.core.model.carousel.CarouselBase;
import com.iqiyi.pps.epg.core.service.carousel.CarouselService;
import com.iqiyi.pps.epg.core.utils.DateTimeUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.sql.Timestamp;
import java.util.Calendar;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.Executors;

/**
 * Created with IntelliJ IDEA.
 * User: jinlin
 * Date: 15-7-7
 * Time: 上午10:56
 * To change this template use File | Settings | File Templates.
 */
public class CarouselUpdateTrigger {
    private static Logger logger = LoggerFactory.getLogger(CarouselUpdateTrigger.class);
    private static final ListeningExecutorService listeningExecutorService =  MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(3));
    @Autowired
    private CarouselService carouselService;

    public void task() {
        logger.info("[CarouselUpdateTrigger] start trigger");
        long startTime = System.currentTimeMillis();
        List<CarouselBase> carouselToUpdate = carouselService.getCarouselToUpdate();
       int createdDay = carouselService.getCarouselCreateDay();
        for(CarouselBase carouselBase: carouselToUpdate) {
            Calendar calendar = Calendar.getInstance();
            Timestamp extendTime = carouselBase.getExtendTime();
//            calendar.setTimeInMillis(extendTime.getTime());
//            calendar.add(Calendar.DATE,1);
            calendar.add(Calendar.DATE,createdDay-1);
            String createStartTime = DateTimeUtil.transLongFormat(calendar.getTimeInMillis());
            try{
                executeRules(carouselBase,"1",createStartTime);
            }catch (Exception e){
                logger.error("执行轮播规则失败：carouselBase id:{}",carouselBase.getId(),e);
            }
//            if(carouselService.checkCopyRightExpire(carouselBase,3)){ //提前3天提醒
//                logger.info("版权到期提醒：carouselBase id:{}",carouselBase.getId());
//            }

            if(carouselService.checkRuleExpire(carouselBase,3)){ //提前3天提醒
                logger.info("规则到期提醒：carouselBase id:{}",carouselBase.getId());
            }

        }
        long endTime = System.currentTimeMillis();
        logger.info("[CarouselUpdateTrigger] trigger end："+(endTime - startTime));
    }

    private void executeRules(final CarouselBase carouselBase, final String createDays,final String createStartTime){
        ListenableFuture<Long> explosion = listeningExecutorService.submit(new Callable<Long>() {
            @Override
            public Long call() throws Exception {
                long start =  System.currentTimeMillis();
                try{
                    carouselService.executeRules(carouselBase,createDays,createStartTime);
                }catch (Exception e){
                    logger.error("执行轮播规则失败：carouselBase id:{},createDays:{},createStartTime:{}"
                            ,carouselBase.getId(),createDays,createStartTime,e);
                }
                logger.info("执行轮播台规则. CarouselBase id:{},time costs:{}ms",carouselBase.getId(), (System.currentTimeMillis()-start));
                return carouselBase.getId();
            }
        });
        Futures.addCallback(explosion, new FutureCallback<Long>() {
            @Override
            public void onSuccess(Long result) {
                logger.info("执行轮播台规则成功. carouselBase id:{},createDays:{},createStartTime:{}"
                        ,result,createDays,createStartTime);
            }

            @Override
            public void onFailure(Throwable t) {
                logger.error("执行轮播规则失败：carouselBase id:{},createDays:{},createStartTime:{}"
                        ,carouselBase.getId(),createDays,createStartTime,t);
            }
        });

    }
}
